﻿using System;
using System.Linq;
using System.Web.Mvc;

namespace TestWebApplication.Models
{
    public abstract class NonSecureController : Controller
    {

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {

            //Only check if we are already on a secure connection and 
            // we don't have a [RequireHttpsAttribute] defined
            if (Request.IsSecureConnection)
            {
                var requireHttps = filterContext.ActionDescriptor
                            .GetCustomAttributes(
                               typeof(RequireHttpsAttribute), false)
                            .Count() >= 1;

                //If we don't need SSL and we are not on a child action
                if (!requireHttps && !filterContext.IsChildAction)
                {
                    var uriBuilder = new UriBuilder(Request.Url)
                    {
                        Scheme = "http",
                        Port = 80
                    };
                    filterContext.Result = Redirect(uriBuilder.Uri.AbsoluteUri);
                }
            }

            base.OnAuthorization(filterContext);
        }

    }

}